package ucuserslogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
)

type ReceiveUserRewardLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewReceiveUserRewardLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReceiveUserRewardLogic {
	return &ReceiveUserRewardLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 领取奖励
func (l *ReceiveUserRewardLogic) ReceiveUserReward(in *pb.ReceiveUserRewardReq) (*pb.ReceiveUserRewardResp, error) {
	defer utils.RecoverPanic()

	var err error
	var ur *usercenter.UserReward
	ur, err = l.svcCtx.UserRewardModel.FindOne(l.ctx, in.Id)
	if err != nil && err != usercenter.ErrNotFound {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if ur == nil {
		l.Logger.Errorf("reward not found ")
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "reward not found")
	}
	var rsp pb.ReceiveUserRewardResp

	if ur.State == userkey.RewardStateCreated {
		rsp.RewardAmount = ur.RewardAmount
		rsp.RewardType = ur.RewardType

		err = l.svcCtx.UserAccountModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
			// 领取奖励
			err2 := l.svcCtx.UserRewardModel.UpdateState(ctx, tx, in.Id, userkey.RewardStateReceived)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			// 更新奖励数量
			err2 = l.svcCtx.UserRewardStatModel.Decr(ctx, tx, in.Uid, 1)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			return nil
		})
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, err
		}
	} else {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "reward state error")
	}

	return &rsp, nil
}
